#TODO encoder en UTF
from os import listdir
from time import sleep

import smtplib  
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
import sys

imagesDirectory = "/home/cedric/Images/motionSurveillance"
def getImageFileNames():
	imageFileNames = [fileName for fileName in listdir(imagesDirectory) if fileName.endswith('.jpg')]
	return imageFileNames

fromAddresse = 'bcedrix@gmail.com'  
toAddresses  = 'bcedrix@gmail.com'  

username = 'bcedrix'  
password = sys.argv[1]

server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username, password)  

currentFileNames = getImageFileNames()

nbCurrentFileNames = len(currentFileNames)
while True:
	newFileNames = getImageFileNames()
	nbNewFileNames = len(newFileNames)
	if nbNewFileNames > nbCurrentFileNames:
		#Il faut envoyer un email
		print "Intrut detecte !"
		print "Sending email..."
		try:
			msg = MIMEMultipart()
			msg['From'] = fromAddresse
			msg['To'] = toAddresses #TODO gerer l'envoi pour plusieurs
			msg['Subject'] = "Intrusion chambre"
			msg.attach(MIMEText("Des mouvements ont ete detectes dans la chambre."))
			for imageFileName in newFileNames:
				if imageFileName not in currentFileNames:
					imageFileName = imagesDirectory + '/'*(imagesDirectory[-1] not in ('/', '\\')) +imageFileName
					msg.attach(MIMEImage(file(imageFileName).read()))
			server.sendmail(fromAddresse, toAddresses, msg.as_string())  
			currentFileNames = newFileNames
			nbCurrentFileNames = nbNewFileNames
			print "Email send !"
		except:
			currentFileNames = newFileNames
			nbCurrentFileNames = nbNewFileNames
			print "Error while sending email"
	sleep(1)

server.quit() 
